package com.app.admin.service;

import com.app.admin.repository.VideoRepository;
import com.app.common.entity.Video;
import com.app.common.utils.FileUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class VideoService {
    private final VideoRepository videoRepository;
    private final FileUtils fileUtils;

    // 初始化存储目录
    public void init() {
        fileUtils.initDirs();
    }

    // 上传视频
    public Video uploadVideo(MultipartFile file, String title, String uploader) throws IOException {
        // 生成唯一文件名（避免重复）
        String originalFileName = file.getOriginalFilename();
        String fileExt = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileName = UUID.randomUUID() + fileExt;

        // 保存视频文件到本地
        String filePath = fileUtils.getVideoStoragePath() + fileName;
        file.transferTo(new File(filePath));

        // TODO：可选，调用FFmpeg获取视频时长和封面（见扩展部分）

        // 保存视频信息到数据库
        Video video = new Video();
        video.setTitle(title);
        video.setFileName(originalFileName);
        video.setFilePath(filePath);
        video.setFileSize(file.getSize());
        video.setStatus(0); // 待审核
        video.setUploadTime(LocalDateTime.now());
        video.setUploader(uploader);
        return videoRepository.save(video);
    }

    // 视频列表（按状态）
    public List<Video> getVideoList(Integer status) {
        if (status != null) {
            return videoRepository.findByStatusOrderByUploadTimeDesc(status);
        }
        return videoRepository.findAllByOrderByUploadTimeDesc();
    }

    // 视频下载
    public void downloadVideo(Long id, HttpServletResponse response) throws IOException {
        Video video = videoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("视频不存在"));

        File file = new File(video.getFilePath());
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {

            // 设置响应头
            response.setContentType("video/mp4");
            response.setContentLength((int) file.length());
            String fileName = URLEncoder.encode(video.getFileName(), StandardCharsets.UTF_8.name());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 写入响应流
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        }
    }

    // 视频审核
    public void auditVideo(Long id, Integer status, String reason) {
        Video video = videoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("视频不存在"));
        video.setStatus(status);
        video.setReason(reason);
        video.setAuditTime(LocalDateTime.now());
        videoRepository.save(video);
    }
}
